package cn.tedu.smartos.base.utils.user;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;

@Slf4j
public class JsonUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将 List<String> 转换为 JSON 字符串
     *
     * @param list 需要转换的列表
     * @return JSON 字符串
     */
    public static String listToJson(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "[]";
        }
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("转换 List<String> 到 JSON 失败", e);
            throw new IllegalArgumentException("列表格式错误");
        }
    }

    /**
     * 将 JSON 字符串转换为 List<String>
     *
     * @param json JSON 字符串
     * @return List<String>
     */
    public static List<String> jsonToList(String json) {
        if (json == null || json.trim().isEmpty()) {
            return Collections.emptyList();
        }
        try {
            return objectMapper.readValue(json, new TypeReference<List<String>>() {});
        } catch (JsonProcessingException e) {
            log.error("解析 JSON 到 List<String> 失败", e);
            return Collections.emptyList();
        }
    }
}